<?php

namespace app\controller\backed;

use app\BaseController;
use app\model\UserCert as UserCertModel;
use app\model\Certificate as CertificateModel;
use app\service\DingNotice as DingNoticeService;
use app\model\DingUser as DingUserModel;

class UserCert extends BaseController
{
    // 证书列表
    public function getUserCerts()
    {
        $params = request()->param();

        $pageNo = isset($params['pageNo']) ? $params['pageNo'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 20;

        $res = UserCertModel::where('user_id = '.$params['uid'])->paginate(
            $pageSize, false, [
            'page' => $pageNo
        ]);

        foreach ($res as $key => &$item) {
            $item['cert_name'] = CertificateModel::find($item['cert_id'])['title'];
        }

        return $this->successMessage('查询成功',$res);
    }

    // 颁发证书
    public function createUserCert()
    {

        $params = request()->param();
        $get_time = date('Y-m-d H:i:s',strtotime($params['get_time']));

        $certs = explode(',', $params['cert_location']);
        $cert_id = array_pop($certs);
        $data=[];
        foreach ($params['uid'] as $v) {
            $data[] = [
                'user_id' => $v,
                'cert_id' => $cert_id,
                'get_time' => $get_time,
                'desc' => $params['desc'],
            ];
        }


        $userCertModel = new UserCertModel();
        $userCertModel->saveAll($data);

        $ding_params = [
            "title" =>  'HR Online消息通知',
            "text" => "您好，在".$get_time."新增一条新证书".CertificateModel::find($cert_id)['title'],
        ];

        $user = DingUserModel::find($params['uid']);
        if($user){
            $dingNoticeService = new DingNoticeService;
            $dingNoticeService->companyMsg($user['id'],'markdown',$ding_params);
        }

        return $this->successMessage('创建成功');

    }

    // 获取证书
    public function getAllCert()
    {
//         之前: 写死只查了两条证书
//        $certificateModel = new CertificateModel();
//        $res0 = $certificateModel->where(['category' => 0])->select();
//        $res1 = $certificateModel->where(['category' => 1])->select();
//
//        $data = [
//            [
//                'id' => 0,
//                'title' => '里程碑证书',
//                'data' => $res0
//            ],
//            [
//                'id' => 1,
//                'title' => '荣耀时刻',
//                'data' => $res1
//            ]
//        ];


        $certificateModel = new CertificateModel();
        $res = $certificateModel->select();

        return $this->successMessage('查询成功',$res);


    }

    public function deleteUserCert()
    {

        $params = request()->param();
        UserCertModel::destroy($params['id']);
        
        return $this->successMessage('删除成功');
    }


}